import md5 from 'md5'
import { postLogin } from '@/api/sys'
import { getProfile } from '@/api/sys'
export default {
  // 独立作用域
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('userInfo') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async login(context, payload) {
      try {
        const res = await postLogin({
          username: payload.username,
          password: md5(payload.password),
          loginType: 'username'
        })
        localStorage.setItem('token', res.token)
        context.commit('setToken', res.token)
        return res.token
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },
    async getUserInfo(context) {
      try {
        const res = await getProfile()
        localStorage.setItem('userInfo', JSON.stringify(res))
        context.commit('setUserInfo', res)
        return res
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },
    logout(context) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      context.commit('setToken', '')
      context.commit('setUserInfo', null)
    }
  }
}
